#define _CRT_SECURE_NO_WARNINGS 1
#include "List.h"


LTNode* BuyLTNode(LTDataType x)
{
	LTNode* newnode = (LTNode*)malloc(sizeof(LTNode));

	if (newnode == NULL)
	{
		printf("malloc fail %d : %s", errno, strerror(errno));
	}
		
	newnode->data = x;
	newnode->prev = NULL;
	newnode->next = NULL;

	return newnode;
}


LTNode* LTInit()
{
	LTNode* phead = BuyLTNode(0);
	phead->next = phead;
	phead->prev = phead;
	return phead;
}

void LTPrint(LTNode* phead)
{
	assert(phead);
	printf("phead<=>");

	LTNode* cur = phead->next;
	while(cur != phead)
	{
		printf("%d<=>",cur->data);
		cur = cur->next;
	}
	printf("\n");
}

void LTPushBack(LTNode* phead, LTDataType x)
{
	assert(phead);

	LTNode* tail = phead->prev;
	LTNode* newnode = BuyLTNode(x);

	newnode->prev = tail;
	tail->next = newnode;

	newnode->next = phead;
	phead->prev = newnode;
}

void LTPopBack(LTNode* phead)
{
	assert(phead);
	assert(phead->next != phead);

	LTNode* cur = phead->prev;
	LTNode* tail = cur->prev;
	free(cur);

	tail->next = phead;
	phead->prev = tail;
}


void LTPushFront(LTNode* phead, LTDataType x)
{
	assert(phead);
	LTNode* newnode = BuyLTNode(x);
	LTNode* first = phead->next;

	phead->next = newnode;
	newnode->prev = phead;
	newnode->next = first;
	first->prev = newnode;
}



void LTPopFront(LTNode* phead)
{
	assert(phead);
	assert(phead->next != phead);

	LTNode* cur = phead->next;
	LTNode* first = cur->next;

	free(cur);
	first->prev = phead;
	phead->next = first;
}


int LTSize(LTNode* phead)
{
	assert(phead);

	LTNode* cur = phead->next;
	int size = 0;
	while (cur != phead)
	{
		size++;
		cur = cur->next;
	}
	return size;
}

LTNode* LTFind(LTNode* phead, LTDataType x)
{
	assert(phead);
	LTNode* cur = phead->next;

	while (cur != phead)
	{
		if (x == cur->data)
		{
			return cur;
		}
		cur = cur->next;
	}
	return NULL;
}

void LTInsert(LTNode* pos, LTDataType x)
{
	assert(pos);

	LTNode* prev = pos->prev;
	LTNode* next = pos;

	LTNode* newnode = BuyLTNode(x);
	newnode->next = next;
	next->prev = newnode;

	newnode->prev = prev;
	prev->next = newnode;

}

LTNode* LTErase(LTNode* pos)
{
	assert(pos);
	assert(pos->next != pos);

	LTNode* posprev = pos->prev;
	LTNode* posnext = pos->next;
	free(pos);

	posprev->next = posnext;
	posnext->prev = posprev;
	return posnext;
}
